package cn.netswap.jeegorilla.framework.common.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by lai_gw on 2020/3/17.
 */
@Component
public class RedisUtils {

    private static RedisTemplate redisTemplate;

    private static StringRedisTemplate stringRedisTemplate;

    /**
     * 将@Autowired 注解到类的构造函数上。很好理解，Spring扫描到AutowiredTypeComponent的bean，然后赋给静态变量component
     * @param redisTemplate
     * @param stringRedisTemplate
     */
    @Autowired
    public RedisUtils(RedisTemplate redisTemplate,StringRedisTemplate stringRedisTemplate){
        this.redisTemplate = redisTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 根据 key 获取key值
     * @return key值
     */
    public static String getStringByKey(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 设置key的值
     * @param key
     * @param value
     */
    public static void setStringByKey(String key, String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }

    /**
     * 根据key 删掉String值
     * @param key
     * @return true 成功删除  false删除失败
     */
    public static Boolean delStringByKey(String key){
       return  stringRedisTemplate.delete(key);
    }

    /**
     *
     * @param key      key
     * @param timeout  时间
     * @param timeUnit  单位
     * @return
     */
    public static Boolean expireKey(String key, long timeout, TimeUnit timeUnit){
        if(StringUtils.isNotBlank(getStringByKey(key)))
            return stringRedisTemplate.expire(key,timeout,timeUnit);
        return false;
    }

    /**
     * 生成一个key 并设置过期时间
     * @param key
     * @param value
     * @param timeout
     * @param timeUnit
     * @return
     */
    public static Boolean setAndExpireKey(String key,String value, long timeout, TimeUnit timeUnit){
        setStringByKey(key,value);
        return expireKey(key,timeout,timeUnit);
    }

    /**
     * 处理分布式锁
     * setnx(key, value)：“set if not exits”，若该key-value不存在，则成功加入缓存并且返回ture，否则返回false。 并设置key的释放时间
     * @param key
     * @param value
     * @param timeout
     * @param timeUnit
     * @return
     */
    public static Boolean setStringNxKey(String key,String value,long timeout,TimeUnit timeUnit){
       Boolean bool = stringRedisTemplate.opsForValue().setIfAbsent(key,value);
       if(bool){
           bool =  expireKey(key,timeout,timeUnit);
           return bool;
       }
       return false;
    }

}
